﻿using System;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Shapes;

using iStudio.Structure.Control.Audio.Editor;
using iStudio.Structure.Wave;

namespace iStudio.Editor.BasicRenderer
{
    public class BasicCachedTrack : EditorCachedTrack
    {
        private readonly Rectangle _trackRectangle;
        private readonly TextBlock _trackName;

        public BasicCachedTrack (WaveTrack track, EditorCore editorCore) : base (track, editorCore)
        {
            //
            // Base rectangle
            //

            _trackRectangle = new Rectangle
                    {
                        Fill = new SolidColorBrush (Color.FromRgb(64, 64, 64)),
                        Stroke = new SolidColorBrush (Color.FromRgb(40, 40, 40)),
                        StrokeThickness = 1,
                        Width = EditorCore.TrackCanvas.RenderSize.Width,
                        Height = 40 * track.WaveFormat.Channels
                    };

            _trackName = new TextBlock
            {
                Margin = new Thickness(10, 10, 0, 0),
                Foreground = new SolidColorBrush(Colors.White)
            };

            _trackName.Inlines.Add(new Run(String.IsNullOrEmpty(track.Name) ? "My track" : track.Name.Trim()));
            _trackName.Inlines.Add(new LineBreak());
            _trackName.Inlines.Add(new Run(((track.WaveFormat.Channels == 1) ? "Mono" : "Stereo") + " " + (track.WaveFormat.SampleRate.ToString("N") + " Hz PCM")));

            EditorCore.TrackCanvas.Children.Add (_trackRectangle);
            EditorCore.TrackCanvas.Children.Add(_trackName);

            foreach (BasicCachedChunk editorChunk in track.TrackChunks.Select(chunk => new BasicCachedChunk(track, chunk, EditorCore)))
            {
                EditorCachedChunks.Add(editorChunk);
            }

            track.PropertyChanged += TrackOnPropertyChanged;
        }

        private void TrackOnPropertyChanged (object sender, PropertyChangedEventArgs propertyChangedEventArgs)
        {
            if (propertyChangedEventArgs.PropertyName == "IsSelected")
            {
                _trackRectangle.Fill = Track.IsSelected ? new SolidColorBrush(Color.FromRgb (86, 86, 86)) : new SolidColorBrush (Color.FromRgb (64, 64, 64));
            }
        }

        public override void SetCanvasProperty(EditorCanvasProperty property, double value)
        {
            base.SetCanvasProperty (property, value);

            if (property == EditorCanvasProperty.MarginTop)
            {
                Canvas.SetTop (_trackRectangle, value);
                Canvas.SetTop (_trackName, value);
            }
        }
    }
}
